package com.atguigu.day09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink06_SQL_Demo {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //2.获取数据
        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));

        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //4.将流转为表(未注册)
//        Table table = tableEnv.fromDataStream(waterSensorStream);

        //注册表(有表名) 从Table对象注册
//        tableEnv.createTemporaryView("sensor", table);
        //直接对流注册为表
        tableEnv.createTemporaryView("sensor", waterSensorStream);


        //将表转为流打印
        //打印测试的方式 一：
//        DataStream<Row> rowDataStream = tableEnv.toAppendStream(resultQueryTable, Row.class);
//
//        rowDataStream.print();

        //方式二：是将Table对象转为TableResult对象进行打印的
//        Table resultQueryTable = tableEnv.sqlQuery("select * from " + table + " where id = 'sensor_1'");
//        TableResult tableResult = resultQueryTable.execute();
//        tableResult.print();

        //方式三：直接获取到TableResult对象进行打印测试
//        TableResult tableResult = tableEnv.executeSql("select id,sum(vc) from " + table + " group by id");
        TableResult tableResult = tableEnv.executeSql("select id,sum(vc) from sensor group by id");
        tableResult.print();

//        env.execute();

    }
}
